<?php

namespace App\Model;

use App\Contract\ContractStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Contract extends Model
{
    use HasFactory, SoftDeletes;

    public $table = 'contract';

    public $guarded = [];

    public $appends = ['expire_status'];

    public $casts = [
       'contract_images' => 'json',
       'created_at' => 'date:Y-m-d H:i:s'
    ];

    public function business()
    {
        return $this->belongsTo(Business::class);
    }

    public function house()
    {
        return $this->belongsTo(House::class);
    }

    public function contractRent()
    {
        return $this->hasOne(ContractRent::class);
    }

    public function contractTenant()
    {
        return $this->hasMany(ContractTenant::class);
    }

    public function masterTenant()
    {
        return $this->hasOne(ContractTenant::class)->where('is_master', 1);
    }

    public function bills()
    {
        return $this->hasMany(Bill::class, 'contract_id', 'id');
    }

    public function contractBreak()
    {
        return $this->hasOne(ContractBreak::class);
    }

    public function getExpireStatusAttribute()
    {
        if ($this->status != ContractStatus::YIQIANYUE && $this->status != ContractStatus::FASTQY) {
            return 0;
        }
        if ($this->expired_at < now()->toDateString()) {
            return 2; // 已过期
        }
        if ($this->expired_at < now()->addDays(7)->toDateString()) {
            return 1; // 7天内到期
        }
        return 0;
    }
}
